package com.vrs.common.context;

import jakarta.servlet.Filter;
import jakarta.servlet.FilterChain;
import jakarta.servlet.ServletRequest;
import jakarta.servlet.ServletResponse;
import jakarta.servlet.http.HttpServletRequest;
import jodd.util.StringUtil;
import lombok.RequiredArgsConstructor;
import lombok.SneakyThrows;

/**
 * @Author dam
 * @create 2024/11/16 16:10
 */
@RequiredArgsConstructor
public class UserTransmitFilter implements Filter {

    @SneakyThrows
    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) {
        HttpServletRequest httpServletRequest = (HttpServletRequest) servletRequest;
        String username = httpServletRequest.getHeader("userName");
        if (StringUtil.isNotBlank(username)) {
            // --if-- username不为空，说明是经过了过滤器的
            Long userId = Long.parseLong(httpServletRequest.getHeader("userId"));
            Integer userType = Integer.parseInt(httpServletRequest.getHeader("userType"));
            UserContext.setUser(new UserInfoDTO(userId, username, userType));
        }
        try {
            filterChain.doFilter(servletRequest, servletResponse);
        } finally {
            // 不移除，会有内存泄漏风险
            UserContext.removeUser();
        }
    }
}